//
//  ST_BTSettingController.swift
//  BTVideo
//
//  Created by DouLei on 2019/8/5.
//  Copyright © 2019 DouLei. All rights reserved.
//

import UIKit
import SwifterSwift
import SnapKit
import SDWebImage
import MBProgressHUD
import SwiftyUserDefaults

class ST_BTSettingController: ST_BTLightBarViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        title_nav_btn.setTitleForAllStates("设置")
        
        view.backgroundColor = Color.white
        
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.top.equalTo(own_navigation_bar.snp.bottom)
            make.bottom.right.left.equalToSuperview()
        }
        
        #if DEBUG
            setupRightBtn()
        #endif
    }
    
    
    fileprivate func setupRightBtn(){
        
        right_nav_btn.isHidden = false
        
        let str = Defaults[.releaseAppApi] ? "👉测试" : "👉正式"
        right_nav_btn.setTitleForAllStates(str)
        right_nav_btn.setTitleColorForAllStates(UIColor.red)
        right_nav_btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        
        right_nav_btn.snp.remakeConstraints { (make) in
            make.right.equalTo(own_navigation_bar).offset(-14)
            make.bottom.equalTo(own_navigation_bar)
            make.height.equalTo(44)
            make.width.equalTo(90)
        }
        
    }
    
    override func right_click() {
        
        Defaults[.releaseAppApi] = !Defaults[.releaseAppApi]
        Defaults.synchronize()
        
        let alert = ST_BTHUDController.init(noticeText: "请重启设备生效!!")
        
        GlobalPresent(toController: alert)
        
        main_thread_execute(afterDelay: 1.5) {
            alert.dismiss(animated: false, completion: nil)
            exit(0)
        }
    }
    
    
//    MARK: - Properties
    lazy var itemWidth:CGFloat = {
        return ScreenWidth
    }()
    
    lazy var itemHeight = 60.cgFloat
    
    lazy var collectionView: UICollectionView = {
        
        let layout = UICollectionViewFlowLayout()
        
        layout.itemSize = CGSize.init(width: itemWidth, height: itemHeight)
        
//        layout.headerReferenceSize = CGSize.init(width: ScreenWidth, height: 65)
        
        layout.minimumLineSpacing = 0
        //        layout.minimumInteritemSpacing = 14
        
        let bottomEdge = iPhoneXSeries ? BTSafeAreaBottom + 30 : 20 + 20
        
//        layout.sectionInset = UIEdgeInsets.init(top: 0, left: 15, bottom: bottomEdge, right: 0)
        
        let collection = UICollectionView(frame: .zero, collectionViewLayout: layout)
        
        collection.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: bottomEdge, right: 0)
        
        collection.register(cellWithClass: ST_OtherGeneralCell.self)
        collection.register(cellWithClass: ST_GeneralOfSwitchCell.self)
        
        
        collection.register(supplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withClass: SettingSectionHeader.self)
        
        collection.delegate = self
        
        collection.dataSource = self
        
        collection.alwaysBounceVertical = true
        
        collection.backgroundColor = Color.white
        
        if #available(iOS 11.0, *) {
            collection.contentInsetAdjustmentBehavior = .never
        }
        return collection
    }()
    
    lazy var data_array:[[ST_OtherGeneralCellModel]] = {
        
        var array2 = [ST_OtherGeneralCellModel]()
        
        let m0 = ST_OtherGeneralCellModel()
        m0.infoKey = "隐私"
        array2.append(m0)
        
        let m01 = ST_OtherGeneralCellModel()
        m01.infoKey = "新消息通知"
        array2.append(m01)
        
//        let model0 = ST_GeneralOfSwitchCellModel()
//        model0.infoKey = "隐身模式"
//        array2.append(model0)
        
        let model4 = ST_OtherGeneralCellModel()
        model4.infoKey = "清除缓存"
        let cacheSize = SDImageCache.shared.totalDiskSize()
        let m = Float(cacheSize)/1024.0/1024.0/10.0
        model4.infoValue = String.init(format: "%0.2fM", m)
        array2.append(model4)
        
        let model5 = ST_OtherGeneralCellModel()
        model5.infoKey = "关于"
        array2.append(model5)
        
        let model6 = ST_OtherGeneralCellModel()
        model6.infoKey = "联系我们"
        array2.append(model6)
        
        
        let model7 = ST_OtherGeneralCellModel()
        model7.infoKey = "注销"
        array2.append(model7)
        
        let model8 = ST_OtherGeneralCellModel()
        model8.infoKey = "退出登录"
        array2.append(model8)
        
        #if DEBUG
        let model9 = ST_OtherGeneralCellModel()
        model9.infoKey = "日志上传"
        array2.append(model9)
        
        
        let model10 = ST_OtherGeneralCellModel()
        model10.infoKey = "设置日志IP地址"
        array2.append(model10)
        
        #endif
        
        
//        return [array1,array2]
        return [array2]
    }()

}

extension ST_BTSettingController:UICollectionViewDataSource,UICollectionViewDelegate{
    
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return data_array.count
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return data_array[section].count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        
        let cellModel = self.data_array[indexPath.section][indexPath.item]
        
        if let m = cellModel as? ST_GeneralOfSwitchCellModel{
            
            let cell = collectionView.dequeueReusableCell(withClass: ST_GeneralOfSwitchCell.self, for: indexPath)
            
            cell.cellModel = m
            
            cell.info_label.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.regular)
            
            return cell
            
        }else{
            
            let cell = collectionView.dequeueReusableCell(withClass: ST_OtherGeneralCell.self, for: indexPath)
            
            cell.cellModel = cellModel
            
            cell.info_label.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.regular)
            
            cell.content_label.textColor = Color.init(hexString: "#999999")
            
            return cell
        }
        
        
        
    }
    
    
    
//    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
//
//        let  view = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withClass: SettingSectionHeader.self, for: indexPath)
//
//
//        if indexPath.section == 0 {
//            view.content_label.text = "通用"
//        }else{
//            view.content_label.text = "其他"
//        }
//
////        view.backgroundColor = Color.random
//
//        return view
//    }
    
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        let item = self.data_array[indexPath.section][indexPath.row]
        
        switch item.infoKey {
        
        case "新消息通知":
            
            guard let a = ST_BTUserInfoManager.shared.additional_attributes else {
                return
            }
            
            let vc = ST_NoticeSettingViewController(accountAdditionalAttributes: a)
            
            self.navigationController?.pushViewController(vc)
            
            break
        case "隐私":
            
            guard let a = ST_BTUserInfoManager.shared.additional_attributes else {
                return
            }
            
            let vc = ST_BTPrivacyViewController(accountAdditionalAttributes: a)
            
            self.navigationController?.pushViewController(vc)
            
            break
        case "弹幕管理":
            let vc = ST_BTBarrageController()
            vc.deleteClosure = { 
//                self?.requestBarrageCount()
            }
            self.navigationController?.pushViewController(vc)
            break
        case "清除缓存":
            
            let hud = MBProgressHUD.showAdded(to: self.view, animated: true)
            
            hud.mode = .indeterminate
            hud.label.text = "清理中"
            
            self.data_array[safe:indexPath.section]?[safe:indexPath.row]?.infoValue = "0M"
            
            self.collectionView.reloadData()
            
            SDImageCache.shared.clearDisk {
                
                hud.label.text = "清理完成"
                
                hud.mode = .text
                
                hud.hide(animated: true, afterDelay: 1.5)
            }
            
            break
        case "关于":
            
            let vc = ST_BTWebViewController()
            
            vc.urlStr = PH.aboutUSURL + "?version="+appVersion
            
            vc.titleStr = "关于"
            
            self.navigationController?.pushViewController(vc)
            
            break
        case "联系我们":
//
//                let pasteboard = UIPasteboard.general
//                pasteboard.string = "bitiankefu"
//
//
//                let alert = BTVerticalAlertViewController.createTianKeFuTalkAlert()
//
//                alert.confirm_closure = {
//
//                    WXApi.openWXApp()
//
//                }
                let alert = ST_SmartSecretaryViewController()
                alert.overCurrentContext = true
                GlobalPresent(toController: alert)
         
            
        break
        case "注销":
            self.sign_out_handle()
        case "隐身模式":
            break
        case "设置日志IP地址":
                changeLogSocketIPAddress()
            break
        case "日志上传":
            
            self.uploadTestLogHandle()
            
            break
        case "退出登录":
            
            
            let alert = UIAlertController.init(title: nil, message: "您确定要退出登录吗？", preferredStyle: UIAlertController.Style.alert)
            
            alert.addAction(title: "确定", style: UIAlertAction.Style.default, isEnabled: true) {[weak self] (action) in
                
                self?.logoutHandle()
                
            }
            
            alert.addAction(title: "取消", style: UIAlertAction.Style.cancel, isEnabled: true) { (action) in
                
//                Crashlytics.sharedInstance().crash()
            }
            
            GlobalPresent(toController: alert)
            
            
            
            break
        default:
            break
        }
        
    }
    
    @objc fileprivate func sign_out_handle() {
        
        self.navigationController?.pushViewController(ST_BTSignOutViewController(), animated: true)
    }
    
    @objc fileprivate func changeLogSocketIPAddress() {
        
        let alertController = UIAlertController(title: "please enter valid ip address", message: "", preferredStyle: .alert)
        
            alertController.addTextField { (textField : UITextField!) -> Void in
                textField.placeholder = Defaults[.logIPAddress].count > 1 ? Defaults[.logIPAddress] : "IP Address"
            }
            let saveAction = UIAlertAction(title: "Save", style: .default, handler: { alert -> Void in
                
                if let textField = alertController.textFields?.first{
                    
                    Defaults[.logIPAddress] = textField.text ?? ""
                    Defaults.synchronize()
                    
                    self.toast(text: "设置成功！！重启手机生效")
                    
                }
            })
        
            let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: { (action : UIAlertAction!) -> Void in })

            alertController.addAction(saveAction)
            alertController.addAction(cancelAction)
            
            self.present(alertController, animated: true, completion: nil)
        
    }
    
    @objc fileprivate func uploadTestLogHandle() {
        
        
        let alert = UIAlertController.init(title: "请选择", message: "日志类型", preferredStyle: .actionSheet)
        
        TIAN_LOG_FILE_ENUM.allCases.forEach { type in
            
            let action = UIAlertAction(title: type.fileName, style: .default) { a in
                self.uploadLog(fileName: type.fileName)
            }
            
            alert.addAction(action)
        }
        
        alert.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
        
        GlobalPresent(toController: alert)
        
    }
    
    fileprivate func uploadLog(fileName:String){
        
        
        let fm = FileManager.default
        
        let localFilePath = fm.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent(fileName)
        
        guard let data = try? Data(contentsOf: localFilePath) else{
            return
        }
        
        let uuid = UUID().uuidString
        
        self.toast(text: "请稍后..")
        
        JVUpload(fileKey:uuid,data: data) { (f) in
            
        } success: { (json) in
            
            let successUrlStr = Defaults[.QNResourcePrefix] + "/" + uuid
            
            let pasteboard = UIPasteboard.general
            
            pasteboard.string = successUrlStr
            
            self.toast(text: "WoW ，路径已经复制到粘贴板 ^_^")
            
        } failure: { (code, error) in
            
            self.toast(text: "WoW ，上传日志错误："+error+"--code:"+code.string)
            
        }

        
    }
    
    /*
    func logoutResetHandle(){
        
        JVrequest(PH.logoutResetApi, success: { (json) in
            
            
            ToastHud(text: "注销账号成功", view: self.view)
            
            
            main_thread_execute(afterDelay: 1.5) {
                self.logoutHandle()
            }
            
            
        }) { (code, err) in
            
            ToastHud(text: err, view: self.view)
        }
        
        
    }*/
    
    
    func logoutHandle()  {
        
        ST_BTUserInfoManager.shared.signOut()
        
        self.navigationController?.popToRootViewController(animated: true)
        
    }
    
}



class SettingSectionHeader: UICollectionReusableView {
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.addSubview(content_label)
        content_label.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(25)
            make.bottom.equalToSuperview().offset(-5)
        }
        
//        self.backgroundColor = Color.random
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    lazy var content_label:UILabel = {
        let control = UILabel.init()
        control.text = ""
        control.textColor = Color.init(hexString: "#999999")
        control.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.semibold)
        return control
    }()
    

}
